package com.tanhua.server.interceptors;

import com.tanhua.domain.db.User;
import com.tanhua.server.exceptions.TanhuaException;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//       执行controller中的方法之前
//        根据token解析出user
        String token = request.getHeader("Authorization");
        User user = userService.getUserByToken(token);
        if(user==null){
            throw new TanhuaException(500,"请重新登录");
        }else{
            UserHolder.setUser(user);
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeFromThreadLocal();
    }
}
